package com.ch.clinking.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.R;
import com.ch.clinking.adapter.MainFragmentStatePagerAdapter;
import com.ch.clinking.adapter.MerListAdapter;
import com.ch.clinking.bean.Merchandise;
import com.ch.clinking.databinding.ActivityMainBinding;
import com.ch.clinking.fragment.MerFragment;
import com.ch.clinking.fragment.MineFragment;
import com.ch.clinking.fragment.OrderFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private List<Merchandise> merchandiseList;
    private MerListAdapter merListAdapter;

    private ClinkingApplication app;

    MineFragment fragmentMine;
    OrderFragment orderFragment;
    MerFragment merFragment;

    MainFragmentStatePagerAdapter fragmentStatePagerAdapter;

    private ActivityResultLauncher<Intent> resultLauncher;

    public Boolean flash = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置状态栏图标为深色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        // 初始化 ActivityResultLauncher
        resultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null) {
                            String updatedMerchandise = data.getStringExtra("updatedMerchandise");
                            String updatedOrder = data.getStringExtra("updatedOrder");
                            String makeOrderFinished = data.getStringExtra("makeOrderFinished");

                            if (updatedMerchandise != null) {
                                // 将数据传递给Fragment
                                Bundle resultBundle = new Bundle();
                                resultBundle.putString("updatedMerchandise", updatedMerchandise);

                                getSupportFragmentManager().setFragmentResult("requestKey", resultBundle);
                            }

                            if (updatedOrder != null) {
                                // 将数据传递给Fragment
                                Bundle resultBundle = new Bundle();
                                resultBundle.putString("updatedOrder", updatedOrder);

                                getSupportFragmentManager().setFragmentResult("updatedOrder", resultBundle);
                            }

                            if (makeOrderFinished != null) {

                                // 刷新OrderList
                                finishedOrderRefreshMerList();

                            }

                        }
                    }
                }
        );

        initDate();
        initEvent();









    }


    private void initDate() {

//        merchandiseList = new ArrayList<>();
//
//        Merchandise merchandise1 = new Merchandise();
//        merchandise1.setTitle("biaoti1");
//        merchandise1.setSkcId("111111111");
//
//        Merchandise merchandise2 = new Merchandise();
//        merchandise2.setTitle("biaoti2");
//        merchandise2.setSkcId("22222222");
//
//        merchandiseList.add(merchandise1);
//        merchandiseList.add(merchandise2);

        app = ClinkingApplication.getInstance();
        //设置非第一次登录
        app.firstLogin = false;
        List<Fragment> fragmentList = new ArrayList<>();

        binding.mainViewPager.setOffscreenPageLimit(2);

        merFragment = MerFragment.newInstance("商品","");
        merFragment.setResultLauncher(resultLauncher);

        orderFragment = OrderFragment.newInstance("下单","");
        orderFragment.setResultLauncher(resultLauncher);

        fragmentMine = MineFragment.newInstance("我的","");

        fragmentList.add(merFragment);
        fragmentList.add(orderFragment);
        fragmentList.add(fragmentMine);



        fragmentStatePagerAdapter = new MainFragmentStatePagerAdapter(getSupportFragmentManager(), fragmentList);
        binding.mainViewPager.setAdapter(fragmentStatePagerAdapter);


    }

    @SuppressLint("NonConstantResourceId")
    private void initEvent(){
//        merListAdapter = new MerListAdapter(this, merchandiseList);
//        binding.merchandiseRecycler.setAdapter(merListAdapter);
//        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
//        binding.merchandiseRecycler.setLayoutManager(layoutManager);


        binding.mainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

            @Override
            public void onPageSelected(int position) {
                toMenuFragment(position);
//                Fragment fragment = fragmentStatePagerAdapter.getItem(position);
//                if (fragment instanceof MerFragment) {
//                    ((MerFragment) fragment).refreshMerchandiseList();
//                }
//                if (fragment instanceof OrderFragment) {
//                    ((OrderFragment) fragment).refreshOrderList();
//                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {}
        });


        binding.bottomNavigationView.setOnItemSelectedListener(item -> {
            switch (item.getItemId()){
                case R.id.navitation_main_mer_list:
                    binding.mainViewPager.setCurrentItem(0);
//                    merFragment.refreshMerchandiseList();
                    break;
                case R.id.navitation_order_list:
                    binding.mainViewPager.setCurrentItem(1);
//                    orderFragment.refreshOrderList();
                    break;
                case R.id.navitation_main_mine:
                    binding.mainViewPager.setCurrentItem(2);
                    break;
                default:
                    break;
            }
            return true;
        });

    }

    private void toMenuFragment(int position) {

        switch (position) {
            case 0:
                binding.bottomNavigationView.setSelectedItemId(R.id.navitation_main_mer_list);

                break;
            case 1:
                binding.bottomNavigationView.setSelectedItemId(R.id.navitation_order_list);
                break;
            case 2:
                binding.bottomNavigationView.setSelectedItemId(R.id.navitation_main_mine);
                break;
            default:
                break;

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void refreshMerAndOrderList() {
        merFragment.refreshMerchandiseList();
        orderFragment.refreshOrderList();
    }

    public void refreshOrderList() {
        flash = true;
        orderFragment.order_changeShopSpinner.setSelection(app.shopPosition);;
    }

    public void refreshMerList() {
        flash = true;
        merFragment.changeShopSpinner.setSelection(app.shopPosition);;
    }

    public void finishedOrderRefreshMerList() {
        flash = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            orderFragment.refreshOrderList();
        }
    }



}